#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：api_automation_test 
@File    ：main.py
@IDE     ：PyCharm 
@Author  ：XiaoDengYa
@Date    ：2021/7/21/021 16:28 
"""

import shutil
import time

import pytest

from common.tools import logger
from common.tools.dingding_push import SendMessage
from common.tools.path_dir import *
from common.tools.read_file import ReadFile
from common.tools.send_email import EmailServe

time_str = time.strftime("%Y-%m-%d_%H_%M", time.localtime())

optput_path = get_optput_path(time_str)
log_path = os.path.join(optput_path, "log")
report_path = os.path.join(optput_path, "report")
zip_file_path = get_optput_path(f"{time_str}.zip")

read = ReadFile()


def run():
    logger.add(os.path.join(log_path, "test.log"), enqueue=True, encoding="utf-8")
    logger.info("""
                     _    _         _      _____         _
      __ _ _ __ (_)  / \\  _   _| |_ __|_   _|__  ___| |_
     / _` | '_ \\| | / _ \\| | | | __/ _ \\| |/ _ \\/ __| __|
    | (_| | |_) | |/ ___ \\ |_| | || (_) | |  __/\\__ \\ |_
     \\__,_| .__/|_/_/   \\_\\__,_|\\__\\___/|_|\\___||___/\\__|
          |_|
          Starting      ...     ...     ...
        """)
    try:
        pytest.main(
            args=[
                "-s", "-v", f"{get_subdirectory_path('case')}",
                f"--alluredir={os.path.join(report_path, 'data')}", "--verbose"
            ]
        )
        os.system(
            f'allure generate {os.path.join(report_path, "data")} -o {os.path.join(report_path, "html")} --clean'
        )
    except Exception as e:
        logger.error("用例执行失败：{}".format(e))
        SendMessage().run_send("测试用例执行失败通知", str(e))
    else:
        shutil.rmtree(os.path.join(report_path, "data"))
        logger.success("测试报告已生成，HTML路径：{}".format(os.path.join(report_path, "html")))
    finally:
        email = read.read_config("email")
        if email.get("on_off") == 'True':
            EmailServe().zip_report(optput_path, zip_file_path)
            EmailServe().send_email(email, zip_file_path)
        else:
            logger.warning("邮件服务未开启，如需开启则到config.yaml下no-off开关打开即可！")


if __name__ == '__main__':
    run()
